<template>
  <view class="contract-detail" v-if="detail">
    <view class="contract-info">
      <u-icon name="home" size="24" @click="goHome"></u-icon>
      <view>
        合同编号：<text>{{ detail.contractNo }}</text>
      </view>
      <!-- <view class="share-btn" @click="share">
        <u-icon name="share-square" size="24"></u-icon>
      </view> -->
    </view>
    <view class="parties-container">
      <view class="party-item">
        <view class="party-info">
          <image src="/static/touxiang.jpg" mode="aspectFill" class="avatar-img"></image>
          <view class="party-name">
            <view class="name">{{ borrower.username }}</view>
            <view class="role" style="background-color: #07c160;color: #fff;">借款人</view>
          </view>
        </view>
        <view class="party-id">
          <view class="id-label">身份证号</view>
          <view class="id-number">{{ maskIdNumber(borrower.idCard) }}</view>
        </view>
      </view>
      <view class="party-item">
        <view class="party-info">
          <image src="/static/touxiang.jpg" mode="aspectFill" class="avatar-img"></image>
          <view class="party-name">
            <view class="name">{{ lender.username }}</view>
            <view class="role" style="background-color: #fb9f70;color: #fff;">出借人</view>
          </view>
        </view>
        <view class="party-id">
          <view class="id-label">身份证号</view>
          <view class="id-number">{{ maskIdNumber(lender.idCard) }}</view>
        </view>
      </view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #f62b2b;" v-if="detail.queryRole === 1 && detail.status === 0" @click="toFace(detail)">待签署</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #f62b2b;" v-if="detail.queryRole === 2 && detail.status === 0" @click="toSignature(detail)">待签署</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #0cb458;" v-if="detail.status === 1">已签署</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #4080ff;" v-if="detail.status === 2">已生效</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #ff8c00;" v-if="detail.status === 3">已逾期</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #2e8b57;" v-if="detail.status === 4">已还款</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #a9a9a9;" v-if="detail.status === 5">已失效</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #800080;" v-if="detail.queryRole === 1 && detail.status === 6" @click="toPay(detail)">待支付</view>
      <view class="party-item" style="width: 22%; display: flex; align-items: center; justify-content: center; color: #0cb458;" v-if="detail.queryRole === 2 && detail.status === 6">已签署</view>

    </view>
    <!-- 欠条详情 -->
    <view class="details-card">
      <view class="card-title">欠条详情</view>

      <view class="detail-row">
        <text class="label">欠款金额</text>
        <text class="value">{{ detail.amount }}元</text>
      </view>

      <view class="detail-row">
        <text class="label">年化利率</text>
        <text class="value">{{ detail.interestRate }}%</text>
      </view>

      <view class="detail-row">
        <text class="label">应收利息</text>
        <text class="value" v-if="detail.repaymentType === 1">{{detail.contractInstallment.totalAmount - detail.amount}}元</text>
        <text class="value" v-if="detail.repaymentType === 0">{{detail.contractLumpSum.interest}}元</text>
      </view>

      <view class="detail-row">
        <text class="label">本息合计</text>
        <text class="value" v-if="detail.repaymentType === 1">{{detail.contractInstallment.totalAmount}}元</text>
        <text class="value" v-if="detail.repaymentType === 0">{{detail.contractLumpSum.totalAmount}}元</text>
      </view>

      <view class="detail-row">
        <text class="label">还款方式</text>
        <text class="value">{{detail.repaymentType === 1 ? '分期还款' : '一次性还本付息'}}</text>
      </view>

      <view class="detail-row" v-if="detail.repaymentType === 0">
        <text class="label">起始日</text>
        <text class="value">{{ formatDate(detail.contractLumpSum.createTime) }}</text>
      </view>

      <view class="detail-row" v-if="detail.repaymentType === 0">
        <text class="label">到期日</text>
        <text class="value">{{ formatDate(detail.contractLumpSum.repaymentDate) }}</text>
      </view>

      <view class="detail-row" v-if="detail.repaymentType === 1">
        <text class="label">分期期数</text>
        <text class="value">{{ detail.contractInstallment.installmentCount }}</text>
      </view>

      <view class="detail-row" v-if="detail.repaymentType === 1">
        <text class="label">每期时长（天）</text>
        <text class="value">{{ detail.contractInstallment.installmentDays }}</text>
      </view>

      <view class="detail-row" v-if="detail.repaymentType === 1">
        <text class="label">每期应还金额</text>
        <text class="value">{{ detail.contractInstallment.eachAmount }}</text>
      </view>

      <view class="detail-row" v-if="detail.repaymentType === 1">
        <text class="label">最后还款日期	</text>
        <text class="value">{{ formatDate(detail.contractInstallment.lastPaymentDate) }}</text>
      </view>

      <view class="detail-row" v-if="detail.repaymentType === 1">
        <text class="label">首次还款日期</text>
        <text class="value">{{ formatDate(detail.contractInstallment.firstPaymentDate) }}</text>
      </view>

      <view class="detail-row">
        <text class="label">欠条原因</text>
        <text class="value">{{ loanReasonName }}</text>
      </view>

      <view class="detail-row">
        <text class="label">备注</text>
        <text class="value">{{ detail.loanDetail }}</text>
      </view>

      <view class="detail-row">
        <text class="label">创建人</text>
        <text class="value" v-if="detail.creatorRole==='lender'">{{detail.lenderName}}</text>
        <text class="value" v-else>{{detail.borrowerName}}</text>
      </view>

      <view class="detail-row" v-if="detail.borrowerSigned === 1 && detail.lenderSigned === 1">
        <text class="label">借款合同</text>
        <text class="value highlight" @click="downloadContract(detail)">下载</text>
      </view>
      <view class="detail-row">
        <text class="label">借款协议</text>
        <text class="value highlight" @click="viewAgreement">查看借款协议</text>
      </view>
    </view>
    <view style="height: 100rpx;"></view>
    <u-popup :show="show" closeable @close="close">
      <view style="padding: 40rpx; display: flex; align-items: center; justify-content: space-around;">
        <view
          style="display: flex;align-items: center;justify-content: center;flex-direction: column; margin-right: 40rpx;"
          @click="shareToWechat">
          <image src="/static/weixin.png" mode="widthFix" style="width: 60rpx;height: 60rpx;" class="avatar-img">
          </image>
          <view style="font-size: 24rpx;color: #333; margin-top: 10rpx;">
            分享到微信
          </view>
        </view>
        <view style="display: flex;align-items: center;justify-content: center;flex-direction: column;"
          @click="shareToMoments">
          <image src="/static/pengyouquan.png" mode="widthFix" style="width: 60rpx;height: 60rpx;" class="avatar-img">
          </image>
          <view style="font-size: 24rpx;color: #333; margin-top: 10rpx;">
            分享到朋友圈
          </view>
        </view>
      </view>
    </u-popup>
    <u-popup :show="showAgreement" mode="center" closeable @close="closeAgreement">
        <view v-html="agreement.content" style="width: 640rpx; height: 1000rpx; padding: 30rpx; overflow-y: scroll;"></view>
    </u-popup>
  </view>
</template>

<script>
import wechat from '@/utils/wechat'

import {apiConfig} from '@/utils/apiConfig'
import { createWeixinJsapiSignature, getContractDetails, getLoanReason, getAgreementType, socialAuthRedirect } from '@/api/user'
export default {
  data() {
    return {
      show: false,
      detail: null,
      lender: {},
      borrower: {},
      loanReason: [],
      agreement: '',
      showAgreement: false
    }
  },
  computed: {
    loanReasonName() {
      return this.loanReason.find(item => item.id === this.detail.loanReasonId)?.name
    }
  },
  async onLoad(options) {
    uni.setStorageSync('REDIRECT_PATH', '')

    getContractDetails({contractId: options.id}).then(res => {
      console.log(res)
      if (res.data.code !== 0) {
        // uni.showToast({
        //   title: res.data.message || '获取合同详情失败',
        //   icon: 'none'
        // })
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/home/index'
          })
        }, 1000)
        return
      }
      this.detail = res.data.data
      this.lender = res.data.data.userInfoList.find(item => item.creatorRole === 'lender')
      this.borrower = res.data.data.userInfoList.find(item => item.creatorRole === 'borrower')
    }).catch(err => {
      console.log('err', err)
      if (err === '401') {
        this.saveCurrentPath()
        uni.navigateTo({
          url: '/pages/login/index'
        })
      } else {
        // uni.showToast({
        //   title: err.message || '获取合同详情失败',
        //   icon: 'none'
        // })
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/home/index'
          })
        }, 1000)
      }
    })
    getLoanReason().then(res => {
      console.log(res)
      this.loanReason = res.data.data
    })
    // 初始化微信JSSDK并设置分享信息
    try {
      await this.initJSSDK()
      await this.setShareInfo()
    } catch (error) {
      console.error('微信JSSDK初始化或分享设置失败:', error)
    }
  },
  methods: {
    downloadContract(data) {
      console.debug(data)
      // data.filePath 是合同pdf文件的url http://s10.v100.vip:30711/admin-api/infra/file/29/get/20250526/6f94f38cee1e99b32cae4bdf5d943d8991691a13f6a3eef080c218fe66410173_1748214795121.pdf
      if (!data.filePath) {
        uni.showToast({
          title: '文件路径不存在',
          icon: 'none'
        });
        return;
      }

      const link = document.createElement('a');
      link.href = data.filePath;
      // 尝试从URL中提取文件名，或者您可以设置一个默认的文件名
      const fileName = data.filePath.substring(data.filePath.lastIndexOf('/') + 1);
      link.download = fileName || 'contract.pdf';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    goHome() {
      uni.switchTab({
        url: '/pages/home/index'
      })
    },
    formatDate(date) {
      // date是时间戳 转为年月日
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    async setShareInfo() {
      console.log('setShareInfo')
      console.log(window.location.href)
      const shareData = {
        title: `借款合同详情 - 合同编号：${this.detail.contractNo || '加载中...'}`,
        desc: '查看借款合同的详细信息，包括借款金额、利率、还款方式等',
        link: window.location.href,
        imgUrl: apiConfig.webUrl+'/static/share.jpeg' // 使用完整URL
      }

      try {
        await wechat.setShareData(shareData)
        console.log('分享信息设置成功')
      } catch (error) {
        console.error('分享信息设置失败:', error)
      }
    },
    saveCurrentPath() {
        const pages = getCurrentPages()
        console.debug('pages', pages)
        if (pages.length > 0) {
            const currentPage = pages[pages.length - 1]
            const route = currentPage.route
            const options = currentPage.options
            console.debug('currentPage', currentPage)
            console.debug('route', route)
            console.debug('options', options)
                // 构建完整的路径
            let fullPath = '/' + route
            if (options && Object.keys(options).length > 0) {
                const params = Object.keys(options).map(key => `${key}=${options[key]}`).join('&')
                fullPath += '?' + params
            }

            console.debug('fullPath', fullPath)
            uni.setStorageSync('REDIRECT_PATH', fullPath)
            console.log('保存重定向路径:', fullPath)
        }
    },
    toPay(data) {
      // 跳转支付页面
      uni.setStorageSync('orderId', data.orderId)
      uni.setStorageSync('contractId', data.contractId)
      this.socialAuthRedirect()
      uni.navigateTo({
        url: '/pages/pay/index?contractId=' + data.id + '&orderId=' + data.orderId
      })
    },
    socialAuthRedirect() {
        socialAuthRedirect({
            type: '31',
            redirectUri: `${window.location.origin}/pages/pay/index`
        }).then(res => {
            window.location = res.data.data
        })
    },
    toSignature(data) {
      uni.navigateTo({
        url: '/pages/loan/signature?contractId=' + data.contractId + '&signatureType=lender'
      })
    },
    toFace(data) {
      uni.navigateTo({
        url: '/pages/face/index?contractId=' + data.contractId + '&name=borrower'
      })
    },
    viewAgreement() {
      // this.showAgreement = true
      uni.navigateTo({
        url: '/pages/contract/agreement?type=loan_agreement'
      })
    },
    maskIdNumber(idNumber) {
      if (!idNumber || idNumber.length < 18) return idNumber;
      return idNumber.substring(0, 3) + '*'.repeat(11) + idNumber.substring(14);
    },
    async initJSSDK() {
      const jssdkConfig = await this.getJSSDKConfig()
      await wechat.initJSSDK(jssdkConfig)
    },
    async getJSSDKConfig() {
      const currentUrl = window.location.href.split('#')[0]
      const res = await createWeixinJsapiSignature({ url: currentUrl })
      return res.data.data
    },
    share() {
      this.show = true
    },
    closeAgreement() {
      this.showAgreement = false
    },
    close() {
      this.show = false
    },
    async shareToWechat() {
      this.show = false
      const shareData = {
        title: `借款合同详情 - 合同编号：${this.detail.contractNo}`,
        desc: '查看借款合同的详细信息，包括借款金额、利率、还款方式等',
        link: window.location.href, // 使用当前页面URL
        imgUrl: apiConfig.webUrl+'/static/share.jpeg' // 使用项目的logo或默认图片
      }

      await wechat.shareToFriend(shareData)
    },
    async shareToMoments() {
      this.show = false
      const shareData = {
        title: `借款合同详情 - 合同编号：${this.detail.contractNo}`,
        link: window.location.href,
        imgUrl: apiConfig.webUrl+'/static/share.jpeg'
      }

      await wechat.shareToTimeline(shareData)
    }
  }
}
</script>

<style lang="scss">
.contract-info {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .contract-number {
    font-size: 28rpx;
    color: #333;
  }
}

.parties-container {
  display: flex;
  margin: 0 15px;
  justify-content: space-between;
  margin-bottom: 20rpx;

  .party-item {
    width: 36%;
    background-color: #fff;
    padding: 20rpx;
    border-radius: 10rpx;
    box-sizing: border-box;

    .party-info {
      display: flex;

      .avatar-img {
        width: 100rpx;
        height: 100rpx;
        margin-right: 10rpx;
      }

      .party-name {
        .name {
          margin-bottom: 10rpx;
          font-size: 28rpx;
        }

        .role {
          padding: 0 10rpx;
          border-radius: 10rpx;
          font-size: 24rpx;
        }
      }
    }

    .party-id {
      margin-top: 20rpx;
      display: flex;
      flex-direction: column;

      .id-label {
        font-size: 24rpx;
        color: #8d8d8d;
      }

      .id-number {
        font-size: 22rpx;
        color: #333;
      }
    }

  }
}

.contract-detail {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding: 0;
}


.details-card {
  background-color: #fff;
  margin: 0 30rpx;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.06);

  .card-title {
    font-size: 40rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 40rpx;
  }

  .detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
      padding-bottom: 0;
    }

    .label {
      font-size: 30rpx;
      color: #666;
      font-weight: 400;
    }

    .value {
      font-size: 30rpx;
      color: #333;
      font-weight: 400;
      text-align: right;

      &.highlight {
        color: #4b91d4;
        font-weight: 600;
        font-size: 28rpx;
      }
    }
  }
}
</style>
